package com.soup.lab.repository;

import com.soup.lab.repository.dao.FruitMapper;
import com.soup.lab.repository.model.Fruit;
import com.soup.lab.tools.mtt.MultiThreadTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class FruitServiceImpl implements FruitService {

    @Autowired
    private FruitMapper fruitMapper;
    @Autowired
    private OtherService otherService;

    @Override
    public void testGetMultiTimes(Integer id) {
        Fruit fruit = fruitMapper.selectByPrimaryKey(id);
        System.out.println("fruit: "+ fruit);
        try {
            TimeUnit.SECONDS.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Fruit fruit1 = fruitMapper.selectByPrimaryKey(id);
        System.out.println("fruit1: "+ fruit1);
    }

    @Override
    public void testGetMultiThread(Integer id) {
        MultiThreadTestUtils.run(3, () -> {
            Fruit fruit = fruitMapper.selectByPrimaryKey(id);
            System.out.println(fruit);
        });
    }

    @Override
    public void testGetThreadPool(Integer id) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CountDownLatch endLatch = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            executorService.submit(() -> {
//                Fruit fruit = fruitMapper.selectByPrimaryKey(id);
//                System.out.println(Thread.currentThread().getId() +": "+ fruit);
                otherService.doSync(id);
                endLatch.countDown();
            });
        }
        try {
            endLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
